﻿Imports System.Configuration
Imports System.IO
Imports ICSharpCode.TextEditor.Document
Imports NewHeaderSystems.Archive.Data

Public Class Main

    Private Const TABLES_SQL As String = "Select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'"

    Private _connectionString As String

    Public Property ConnectionString() As String
        Get
            Return _connectionString
        End Get
        Set(ByVal value As String)
            _connectionString = value
        End Set
    End Property


    Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SetupTextBox()
        My.Application.SaveMySettingsOnExit = True
        txtSql.Text = My.Settings.SavedSql

        OpenDatabase(GetApplicationConfigurationString())
    End Sub

    Private Sub RunSql()
        Try

            Dim sql As String = txtSql.Text
            Dim selecedText = txtSql.ActiveTextAreaControl.SelectionManager.SelectedText.Trim()
            If selecedText.Length > 0 Then sql = selecedText
            tsLabel.Text = ""
            If sql.Trim().Length <> 0 Then
                My.Settings.SavedSql = txtSql.Text
                My.Settings.Save()
                dgResults.DataSource = Nothing
                tsLabel.Text = "Running..."
                Application.DoEvents()
                dgResults.DataSource = DataScript.ExecuteQuery(ConnectionString, sql)
                tsLabel.Text = "Command completed successfully."
            End If
        Catch ex As Exception
            tsLabel.Text = ex.Message
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Function GetApplicationConfigurationString() As String
        Dim connection As String = String.Empty
        Try
            connection = ConfigurationManager.OpenExeConfiguration(Path.Combine(Application.StartupPath, "NewHeaderSystems.Archive.exe")).ConnectionStrings.ConnectionStrings("NewHeaderSystems.Archive.Data.My.MySettings.NHSArchiveConnectionString").ConnectionString
        Catch ex As Exception

        End Try
        Return connection
    End Function

    Private Sub CustomizeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomizeToolStripMenuItem.Click
        RunSql()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        If openFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
            OpenDatabase(DataScript.GetConnectionString(openFileDialog.FileName))
        End If
    End Sub

    Private Sub OpenDatabase(ByVal connection As String)
        Try
            Me.Cursor = Cursors.WaitCursor
            ShowSchema(connection)
            ConnectionString = connection 'Remember the connection string only if we opened and loaded the schema succesfully.
            tsLabel.Text = DataScript.GetFileNameFromConnectionString(connection)
            Me.Cursor = Cursors.Default

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MessageBox.Show(ex.Message, "Cannot Open Database", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ShowSchema(ByVal connection As String)
        Dim tablesList As DataTable = DataScript.ExecuteQuery(connection, TABLES_SQL)

        treeView.Nodes.Clear()
        Dim filePath = DataScript.GetFileNameFromConnectionString(connection)
        Dim rootNode = treeView.Nodes.Add("DB", Path.GetFileName(filePath), 0, 0)
        rootNode.ToolTipText = filePath
        Dim tablesNode = rootNode.Nodes.Add("Tables", "Tables", 1, 1)
        For Each row As DataRow In tablesList.Rows
            Dim tableName As String = row(0).ToString()
            tablesNode.Nodes.Add(tableName, tableName, 2, 2)
        Next
        treeView.ExpandAll()
    End Sub

    Private Sub SetupTextBox()
        Dim strPathXSHD As String = My.Application.Info.DirectoryPath
        Dim provider As New FileSyntaxModeProvider(strPathXSHD)
        Dim manager As HighlightingManager = HighlightingManager.Manager
        manager.AddSyntaxModeFileProvider(provider)
        txtSql.Document.HighlightingStrategy = manager.FindHighlighter("SQL")

        With txtSql
            .Font = New Font("Courier New", 9, FontStyle.Regular)
            .ShowEOLMarkers = False
            .ShowInvalidLines = False
            .ShowSpaces = False
            .ShowTabs = False
            .ShowVRuler = False
            .ShowHRuler = False
            .IsIconBarVisible = False
            .ShowLineNumbers = True
            .AutoScroll = True
        End With
    End Sub
End Class
